package com.xing.Utils;

import java.lang.reflect.Field;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2023/12/3 22:23
 */
public class MyUtils {
    public static <T>T entity(Object entity, T DTO) throws Exception {
        Class change = entity.getClass();
        String changeType = change.getSimpleName();
        Field[] declaredFields = change.getDeclaredFields();
        Class<?> dto =  DTO.getClass();
        for (Field field : declaredFields) {
            //禁止访问entity控制权限
            field.setAccessible(true);
            //获取entity属性名
            String name = field.getName();
            //获取entity属性类型
            Class<?> fieldType = field.getType();
            //获取entity属性值
            Object cast = fieldType.cast(field.get(entity));
            //获取DTO对象的属性
            try {
                dto.getDeclaredField(name);
            }catch (NoSuchFieldException e) {
                continue;
            }
            Field fieldDTO = dto.getDeclaredField(name);
            //获取DTO对应属性类型
            Class<?> fieldDTOType = fieldDTO.getType();
            if (fieldDTOType==fieldType){
                //禁止访问DTO控制权限
                fieldDTO.setAccessible(true);
                //对DTO对应属性赋值
                fieldDTO.set(DTO,cast);
            }
        }
        return DTO;
    }
}
